# 准达咨询 http://www.ometal.com/

import requests
import parsel
import common.dataBase as db


def get_data(html_url):
    response = requests.get(html_url)
    selector = parsel.Selector(response.text)
    table = selector.css('table tr td::text').getall()
    table_data = table[9:-4]
    return table_data


def save_all(name, url):
    table_data_all = get_data(url)
    length = int(len(table_data_all) / 4)
    insert_sql = []
    for i in range(length):
        price = table_data_all[i * 4 + 2]
        price_range = table_data_all[i * 4 + 1]
        time = table_data_all[i * 4 + 0]
        insert_sql.append(
            f'INSERT INTO mat_price VALUES (null, "{name}", "{price}","{price_range}", "{time}", "{url}")')
    db.save(insert_sql)


def save_today(name, url):
    table_data = get_data(url)
    insert_sql = []
    price = table_data[-2]
    price_range = table_data[-3]
    time = table_data[-4]
    insert_sql.append(
        f'INSERT INTO mat_price VALUES (null, "{name}", "{price}","{price_range}", "{time}", "{url}")')
    db.save(insert_sql)


if __name__ == '__main__':
    save_today('1#铜', 'http://app.ometal.cn/data/month_data.asp?pid=820')
    save_today('1#锡', 'http://app.ometal.cn/data/month_data.asp?pid=832')
